<template>
  <div
      :style="{
    left:posX+'px',
    top:posY+'px',
    width:width,
    background:background,
    zIndex:zIndex,
    boxShadow:showShadow ? boxShadow : '',
    menuStyle
  }"
      class="menu-view"
      v-show="visible">
    <slot>
      <XContextmenuItem
          v-for="(item,index) in list"
          @onClick="item.clickFn">
        {{item.title}}
      </XContextmenuItem>
    </slot>
  </div>
</template>

<script>
import XContextmenuItem from "@/components/xcontextmenu/XContextmenuItem";
export default {
  name: "XContextmenu",
  components: {XContextmenuItem},
  props:{
    posX:{
      type:Number,
      default: -1
    },
    posY:{
      type:Number,
      default: -1
    },
    visible:{
      type:Boolean,
      default:false
    },
    list:{
      type:Array,
      default:[]
    },
    width:{
      type:String,
      default:"100px"
    },
    background:{
      type:String,
      default:"white"
    },
    zIndex:{
      type:Number,
      default:99
    },
    showShadow:{
      type:Boolean,
      default:true
    },
    boxShadow:{
      type:String,
      default:"0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)"
    },
    menuStyle:{
      type:Object,
      default:function (){}
    }
  },
  data(){
    return{

    }
  },
  methods:{
    closeContextmenu(event) {
      this.visible = false;
    },
    bodyClick(){
      document.body.addEventListener("click",this.closeContextmenu);
      document.body.addEventListener("contextmenu",this.closeContextmenu);
    },
    removeBodyClick(){
      document.body.removeEventListener("click",this.closeContextmenu);
      document.body.removeEventListener("contextmenu",this.closeContextmenu);
    },
    showContextMenu(event){
      event.stopPropagation();
      event.preventDefault();
      this.visible = false
      this.posX = event.x
      this.posY = event.y
      this.visible = true
    },
    hideContextMenu(){
      if (this.visible){
        this.visible = false
      }
    }
  },
  beforeDestroy() {
    this.removeBodyClick()
  },
  mounted() {
    this.bodyClick()
  }
}
</script>

<style scoped lang="scss">
.menu-view{
  position: fixed;
  height: auto;
  z-index: 9999!important;
}
</style>
